import pymysql
import threading
lock = threading.Lock()
class DB:
    # 初始化方法
    def __init__(self) -> None:
        self.conn = pymysql.connect(host="47.104.108.172", port=3339,
                                    db="p2p", charset="utf8", user="root", password="123456",
                                    cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    def reConnect(self):
        try:
            self.conn.ping()
        except:
            self.conn = pymysql.connect(host="47.104.108.172", port=3339,
                                        db="p2p", charset="utf8", user="root", password="123456",
                                        cursorclass=pymysql.cursors.DictCursor)
            self.cursor = self.conn.cursor()

    # 添加修改
    def add(self, sql):
        self.cursor.execute(sql)

    # 获取单条
    def findone(self, sql):
        lock.acquire()
        self.reConnect()
        self.cursor.execute(sql)
        res = self.cursor.fetchone()
        lock.release()
        return res

    # 获取多条
    def findAll(self, sql):
        lock.acquire()
        self.reConnect()
        self.cursor.execute(sql)
        res = self.cursor.fetchall()
        lock.release()
        return res

    def commit(self):
        self.conn.commit()

    def rollback(self):
        self.conn.rollback()

    # 关闭
    def close(self):
        self.cursor.close()
        self.conn.close()

    def update1(self, sql):
        self.cursor.execute(sql)

    def update(self, sql):
        self.cursor.execute(sql)
        self.conn.commit()
        return self.cursor.lastrowid
db = DB()